/**
 * @description user控制类
 * @author 盘古他爹
 */

import { ILogin } from "./types"
import {Restfull} from "../../config/resModel"
import UserService from "../../service/user";//User模型服务

import { Bcrypt } from "../../utils/bcryptjs"
import { ErrorNamePwd,ErrorUserName } from "../../config/resCodeMsg"; //错误码
import { JWT } from "../../utils/jwt"; //引入JWT
import { C, N } from "../../config/commonTypes"
import { set } from "../../redis"
type data = {}
class _UserCON {
    // login: IFs<Koa.Context, Koa.Next>
    async login(ctx: C) {
        //参数
        const { userName, password } = ctx.request.body
        console.log("query:", userName, password);

        //上数据库查找数据
        //通过用户名查找，是否存在
        const isExist = await UserService.getUserInfo<ILogin>({ userName })
        if (isExist) {
            //如果存在，比对密码
            const compareRes = Bcrypt.compareHash(password, isExist.password);
            console.log("比较结果", compareRes, isExist, '类习惯', typeof isExist);
            const token = JWT.JwtSign(isExist.toJSON());
            delete isExist.password
            const info = {
                userName,
                nickname: isExist.nickname,
                role: isExist.role,
                token,
                isDM:isExist.isDM,
                avatar:isExist.avatar,
                id:isExist.id
            }
            ctx.body = compareRes ? Restfull.success<data>(info, `登陆成功,欢迎${isExist.nickname}回来！`) : Restfull.faild(ErrorNamePwd);
            // set(userName, token)
        } else {
            ctx.body = Restfull.faild(ErrorNamePwd)
        }

    }


    //用户注册
    async register(ctx: C) {
        const { userName, password,nickname,avatar } = ctx.request.body
        console.log("query:", userName, password);
        const isExist = await UserService.getUserInfo<ILogin>({ userName })
        if (isExist) {
            ctx.body = Restfull.faild(ErrorUserName)
        } else {
            const register = await UserService.registerUser({
                userName, password:Bcrypt.hashStr(password),nickname,avatar 
            })
            ctx.body = {
                code:200,
                msg:"注册成功",
                data:{}
            }
        }
    }
}


const UserCON = new _UserCON()

export {
    UserCON
}